﻿#include "ssMsgThread.h"
#include "../tools/ssTools.h"
#include "../time/ssTimer.h"
//#include <cstdio>

namespace StarSeeker
{

ssMsgThread::ssMsgThread()
{
	m_maxMsgCount = 100000;
	//m_condPut.BindLock(&m_mutex);
	m_condGet.BindLock(&m_mutex);
}

ssMsgThread::~ssMsgThread()
{
	ExitThread();
	//printf("CAO\n");
}

bool ssMsgThread::PostMsg(ssMsg_s &m)
{
	if (m_msgList.Size() > m_maxMsgCount)
	{
		return false;
	}
	SS_MUTEX_LOCK(m_mutex) //锁定互斥量
	//while (m_msgList.Size() >= m_maxMsgCount)
	//{
	//	//printf("put wait\n");
	//	m_condPut.Wait(); //条件变量等待
	//}
	m_msgList.PushBack(m);
	//printf("put\n");
	m_condGet.NotifyAll(); //通知可以读取数据
	SS_MUTEX_UNLOCK(m_mutex)

	return true;
}

bool ssMsgThread::PostMsg(u32 msgID, u32 subID, ulint param1, ulint param2, ulint param3)
{
	ssMsg_s msg(msgID, subID, param1, param2, param3);
	return PostMsg(msg);
}

void ssMsgThread::ThreadMemberFunc()
{
	OnThreadRun();
	while (!IsRequestStop())
	{
		SS_MUTEX_LOCK(m_mutex); //锁定互斥量
		while (m_msgList.Size()==0)
		{
			//printf("get wait\n");
			m_condGet.Wait(); //条件变量等待
		}
		m_tempList = m_msgList;
		m_msgList.Empty();
		SS_MUTEX_UNLOCK(m_mutex);
		//m_condPut.NotifyAll(); //通知可以写入数据

		u32 now = ssTime::GetTimeNow().u32p;
		ssList<ssMsg_s>::Iterator itr = m_tempList.Begin();
		while(itr.IsVaild())
		{
			if (itr.Data()->msgID == SS_THREAD_STOP)
			{
				RequestStop();
				break;
			}
			else if (itr.Data()->msgID == SS_TIMER_ONCE)
			{
				if (now > itr.Data()->subID)
				{
					HandleMessage(*itr);
				}
				else
				{
					SS_MUTEX_LOCK(m_mutex)
						m_msgList.PushBack(*itr);
					SS_MUTEX_UNLOCK(m_mutex)
				}
			}
			else
			{
				HandleMessage(*itr.Data());
			}
			++itr;
		}
		//printf("get%d\n", m_tempList.Size());
		m_tempList.Empty();
	}
}

void ssMsgThread::ExitThread()
{
	ssMsg_s m;
	m.msgID = SS_THREAD_STOP;
	PostMsg(m);
	ssThreadBase::Sleep(100);
	WaitForExit();
}

void ssMsgThread::SetMaxMsgCount(u32 ct)
{
	m_maxMsgCount = ct;
}

StarSeeker::u64 ssMsgThread::GetMsgCount()
{
	u32 c1 = (u32)m_msgList.Size();
	u32 c2 = (u32)m_tempList.Size();
	return U32MergeU64(c1, c2);
}

}
